<?php

namespace App\Services;


use App\Models\User as UserModel;
use App\Utils\Tools;
use EasyWeChat\MiniApp\Application;
use App\Utils\RedisUtils;
use App\Models\UserPointRecords;

class UserService extends UserModel
{
    protected function getConfig(): array
    {
        $wechat = config('wechat.mini_program');
        return [
            'app_id' => $wechat['app_id'],
            'secret' => $wechat['secret'],
            'mch_id' => $wechat['pay']['mch_id'],
            'http' => [
                'throw' => true, // 状态码非 200、300 时是否抛出异常，默认为开启
                'timeout' => 5.0,
            ],
        ];
    }

    /**微信小程序登录
     * @param $param
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     */
    public function xcxLogin($param)
    {
        $code = $param['code'];
//        $wechat = new Application($this->getConfig());
//        // 获取 session_key 和 openid
//        $result = $wechat->getUtils()->codeToSession($code);
//        if (!isset($result['openid']) || !$result['openid']) {
//            throwError('授权失败');
//        }
//        $phone = $this->getPhone($param['phone_code']);
        $phone = '17637635895';
        $token = SetToken();
        if (!$user = $this->where(['phone' => $phone])->first()) {
            $user = $this;
            $user->openid = $result['openid'];
            $user->phone = $phone;
            $user->nickname = '微信用户';
            $user->avatar = 'https://miaoyao-oss.oss-cn-hangzhou.aliyuncs.com/miaoyao/cat/avatar.png';
            $user->save();
        }
        //更新一下openid
        if (!$user->openid) {
            $user->openid = $result['openid'];
            $user->save();
        }
        RedisUtils::setUserInfo($token, $user);
        SetReturnJson(['token' => $token, 'isBindMobile' => $user['phone'] ? 1 : 0]);
    }

    /**小程序授权绑定手机号
     * @param $param
     * @return void
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function wxBindMobile($param)
    {
        $user = getUser();
        $user->phone = $this->getPhone($param['phone_code']);
        $user->save();
        SetReturnJson([]);
    }

    /**获取手机号
     * @param $phone_code
     * @return mixed|void
     * @throws \EasyWeChat\Kernel\Exceptions\HttpException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidArgumentException
     * @throws \EasyWeChat\Kernel\Exceptions\InvalidConfigException
     * @throws \EasyWeChat\Kernel\Exceptions\RuntimeException
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    protected function getPhone($phone_code)
    {
        $data['code'] = $phone_code;
        $wechat = new Application($this->getConfig());
        $phone_info = $wechat->getClient()->postJson('wxa/business/getuserphonenumber', $data);
        if (isset($phone_info['phone_info']['phoneNumber']) && $phone_info['phone_info']['phoneNumber']) {
            return $phone_info['phone_info']['phoneNumber'];
        }
        throwError('手机号授权失败');
    }

    /**用户信息
     * @return void
     */
    public function getUserInfo()
    {
        $user = getUser();
        SetReturnJson([
            'nickname' => $user->nickname,
            'avatar' => $user->avatar,
            'phone' => $user->phone,
            'point' => $user->point,
        ]);
    }

    /**修改个人呢信息(昵称 头像)
     * @param $param
     * @return void
     */
    public function editUser($param)
    {
        $user = getUser();
        $user->nickname = $param['nickname'];
        $user->avatar = $param['avatar'];
        $user->save();
        SetReturnJson([]);
    }

    /**积分流水
     * @param $param
     * @return void
     */
    public function getPointRecords($param)
    {
        $user = getUser();
        $type = $param['type'] ?? 0;
        $size = isset($param['size']) && $param['size'] ? $param['size'] : 20;
        $query = UserPointRecords::where(['wx_user_id' => $user->id]);
        if ($type) {
            $query->where(['change_mode' => $type]);
        }
        $pointRecords = $query->orderBy('created_at', 'desc')->paginate($size);
        SetReturnJson($pointRecords);
    }
}
